﻿using System;
using System.Net.Sockets;

namespace BodaNetCommunications.Extensions
{
    public static class SocketExtension
    {
        /// <summary>
        /// 判断Socket是否处于连接状态
        /// </summary>
        /// <param name="socket"></param>
        /// <returns> True:连接状态; False:断开连接 </returns>
        public static bool IsConnectedExt(this Socket socket)
        {
            if (socket == null) return false;

            //  if (_socket == null || !_socket.Connected || ((_socket.Poll(200, SelectMode.SelectRead) && (_socket.Available == 0))))
            var isConnected = (!(!socket.Connected || (socket.Poll(200, SelectMode.SelectRead) && (socket.Available == 0))));
            return isConnected;
        }

        /// <summary>
        /// 判断Socket是否连接失败
        /// </summary>
        /// <param name="socket"></param>
        /// <returns></returns>
        /// <exception cref="Exception">True:连接失败; False:连接成功</exception>
        public static bool IsConnectFailedExt(this Socket socket)
        {
            if (socket == null || !socket.Connected || ((socket.Poll(200, SelectMode.SelectRead) && (socket.Available == 0))))
            {
                return true;
            }
            return false;
        }
    }
}